package com.bolingcavalry.crm.taskorder.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.base.PageResult;
import com.base.ResponseResult;

import com.bolingcavalry.crm.taskorder.service.TaskorderService;
import com.dto.TaskOrderDTO;
import com.vo.TaskOrderVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Api("任务单管理")
@RestController
@RequestMapping("/taskorder")
@Slf4j
public class TaskorderController {

    @Autowired
    private TaskorderService taskOrderService;

    /**
     * 新建任务单
     */
    @PostMapping("/add")
    @ApiOperation("新增任务单")
    public ResponseResult add(@RequestBody TaskOrderDTO taskOrderDTO) {
        log.info("新增任务单: {}", taskOrderDTO);
        if (taskOrderService.add(taskOrderDTO)) {
            return ResponseResult.success("添加任务单成功");
        }
        return ResponseResult.error("添加任务单失败");
    }

    /**
     * 根据ID获取任务单详情
     */
    @GetMapping("/get/{id}")
    @ApiOperation("根据ID获取任务单")
    public ResponseResult<TaskOrderVO> getById(@PathVariable Long id) {
        log.info("获取任务单ID: {}", id);
        return ResponseResult.success(taskOrderService.getById(id));
    }

    /**
     * 根据售后编号获取任务单详细
     */
    @GetMapping("/getByTaskOrderNumber/{orderNumber}")
    @ApiOperation("根据售后编号获取任务单")
    public ResponseResult<TaskOrderVO> getByOrderNumber(@PathVariable String orderNumber) {
        log.info("获取任务单ID: {}", orderNumber);
        return ResponseResult.success(taskOrderService.getByOrderNumber(orderNumber));
    }

    /**
     * 上传任务单图片并归档
     */
    @PostMapping("/updateByImage")
    public ResponseResult<TaskOrderVO> updateByImage(@RequestBody MultipartFile image) throws Exception {
        //返回一个url
        TaskOrderVO taskOrderVO = taskOrderService.updateByImage(image);
        return ResponseResult.success(taskOrderVO);
    }

    /**
     * 生成Excel
     * @param id 传入的任务单ID
     */
    @GetMapping("/generateExcel/{id}")
    @ApiOperation("生成Excel")
    public void generateExcel(@PathVariable Long id) throws Exception {
        log.info("生成Excel: {}", id);
        taskOrderService.generateExcel(id);
    }

    @GetMapping("/download-excel/{id}")
    @ApiOperation("下载Excel")
    @CrossOrigin(origins = "*")
    public void downloadExcel(@PathVariable Long id, HttpServletResponse response) {
        try {
            taskOrderService.generateExcel(id, response);
        } catch (Exception e) {
            log.error("下载Excel失败，任务单ID: {}", id, e);
        }
    }

    /**
     * 修改任务单
     */
    @PostMapping("/update")
    @ApiOperation("修改任务单")
    public ResponseResult update(@RequestBody TaskOrderDTO taskOrderDTO) {
        log.info("修改任务单: {}", taskOrderDTO);
        return taskOrderService.update(taskOrderDTO);
    }

    /**
     * 修改任务单状态
     */
    @PostMapping("/updateStatus")
    @ApiOperation("修改任务单状态")
    public ResponseResult updateStatus(
            @RequestBody TaskOrderDTO taskOrderDTO) {
        log.info("修改任务单状态: {}, ID: {}", taskOrderDTO.getStatus(), taskOrderDTO.getId());
        return taskOrderService.updateStatus(taskOrderDTO.getId(), taskOrderDTO.getStatus());
    }


    /**
     * 分页条件查询任务单
     */
    @GetMapping("/list")
    @ApiOperation("分页条件查询任务单")
    public ResponseResult<IPage<TaskOrderVO>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String customerName, // 客户公司名（用于模糊查询）
            @RequestParam(required = false) String technicalManagerName, // 技术负责人姓名
            @RequestParam(required = false) String receiverName,
            @RequestParam(required = false) String businessManagerName, // 商务负责人姓名
            @RequestParam(required = false) String taskOrderNumber, // 任务单单号
            @RequestParam(required = false) String startDate, // 开始时间
            @RequestParam(required = false) String endDate, // 结束时间
            @RequestParam(required = false) String status
    ){
        log.info("分页查询任务单");
        IPage<TaskOrderVO> page = taskOrderService.getByPage(pageNum, pageSize, customerName, technicalManagerName,receiverName, businessManagerName, taskOrderNumber, startDate, endDate, status);
        PageResult<TaskOrderVO> result = new PageResult<>();
        result.setTotal(page.getTotal());
        result.setPages((int) page.getPages());
        result.setCurrent((int) page.getCurrent());
        result.setSize((int) page.getSize());
        result.setRecords(page.getRecords());
        return ResponseResult.success("查询成功",result);
    }

    /**
     * 批量逻辑删除任务单
     */
    @PostMapping("/batchdelete")
    @ApiOperation("批量逻辑删除任务单")
    public ResponseResult batchDelete(@RequestParam List<Long> ids) {
        log.info("批量删除任务单: {}", ids);
        if (taskOrderService.batchDelete(ids)) {
            return ResponseResult.success("批量删除成功");
        }
        return ResponseResult.error("删除失败，当前状态不允许删除");
    }
}